import { errResponse, checkRequire } from '../../utils/utils';
import { VoteUser } from '../../entity/voteuser.entity';
import { getManager, Repository } from 'typeorm';

/**
 * @apiDefine myInfoCtrl
 * @apiParam {String} test 用户名1111.
 */
export class LoginCtrl {
  public static async index(ctx: any) {
    // 获取post参数
    const params = ctx.request.body;
    console.log(params);
    const require = ['username', 'password'];
    const userRepository: Repository<VoteUser> = getManager().getRepository(
      VoteUser
    );
    const userData: VoteUser = new VoteUser();
    // 检查参数是否缺失
    const isRequire = checkRequire(require, params);
    if (isRequire !== true) {
      errResponse(ctx, 400, `缺少参数${isRequire}`);
      return;
    }
    userData.u_name = params.username;
    userData.u_password = params.password;
    const usernameExist = await userRepository.findOne({
      u_name: userData.u_name
    });
    console.log(usernameExist);
    // 判断用户名是否存在
    if (!usernameExist) {
      errResponse(ctx, 400, '用户名不存在！');
    } else {
      // 判断密码是否正确
      if (userData.u_password === usernameExist.u_password) {
        ctx.status = 200;
      } else {
        errResponse(ctx, 400, '密码错误！');
      }
    }
  }
}
